<?php


/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class PasswordForm extends CFormModel {
	public $password;
	public $password_new;
	public $password_check;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules() {
		return array (
			// username and password are required
			array (
				'password, password_new, password_check',
				'required'
			),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels() {
		return array (
			'password' => Yii::t('userinfo', 'Type your current password'),
			'password_new' => Yii::t('userinfo', 'Type your new password'),
			'password_check' => Yii::t('userinfo', 'Type your password again')
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function save() {
		if (!$this->hasErrors()) // we only want to authenticate when no input errors
			{
			$identity = new UserIdentity(Yii::app()->user->id, $this->password);
			$identity->authenticate();
			switch ($identity->errorCode) {
				case UserIdentity::ERROR_NONE :
					// I check the new password equality
					if ($this->password === $this->password_new) {
						// Old and new password are identicals
						$this->addError('password_new', Yii::t('userinfo', 'The new password you entered is the same than the current. Enter a new one.'));
					} else {
						if ($this->password_new !== $this->password_check) {
							$this->addError('password_check', Yii::t('userinfo', 'The new password and the checked input are differents.'));
						} else {
							$identity->getUser()->password = md5($this->password_new);
							if (!$identity->getUser()->save())
							{
								$this->addErrors($identity->getUser()->getErrors());
							}
						}
					}
					break;
				case UserIdentity::ERROR_USERNAME_INVALID :
					Yii::app()->user->logout();
					$this->redirect(Yii::app()->homeUrl);
					break;
				default : // UserIdentity::ERROR_PASSWORD_INVALID
					$this->addError('password', Yii::t('userinfo', 'Current password is incorrect.'));
					break;
			}
		}

		return !$this->hasErrors();
	}
}
?>
